package com.link.play.fit.ai.ui.vip

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.VideoView
import androidx.activity.addCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.android.billingclient.api.ProductDetails
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.vipProductWeek
import com.link.play.fit.ai.RemoteConfig.vipProductYear
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.databinding.AcVipBuyDesLayoutBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.FIRBASE_SUB_PRODUCT_ID
import com.link.play.fit.ai.kv.AuthCache.SUB_CURRENCY
import com.link.play.fit.ai.kv.AuthCache.SUB_PRICE_VALUE
import com.link.play.fit.ai.kv.AuthCache.SUB_PRODUCT_ID
import com.link.play.fit.ai.utils.GooglePayUtil
import com.link.play.fit.ai.utils.GooglePayUtil.calculateSavingsPercentageFromStrings
import com.link.play.fit.ai.utils.GooglePayUtil.defaultWeekPrice
import com.link.play.fit.ai.utils.GooglePayUtil.defaultYearPrice
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToMonth
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToWeekDay
import com.link.play.fit.ai.utils.GooglePayUtil.google_pay_id
import com.link.play.fit.ai.utils.GooglePayUtil.parsePriceString
import com.link.play.fit.ai.utils.OpenAgreementUtils
import com.link.play.fit.ai.utils.ScreenUtil
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale


class VipBuyDesAc : BaseActivity<AcVipBuyDesLayoutBinding>(AcVipBuyDesLayoutBinding::inflate) {
    private var yearSubscriptionOfferDetails: List<ProductDetails.SubscriptionOfferDetails>? = null
    private var yearProductDetails: ProductDetails? = null
    private var yearFormattedPrice = ""

    private var monthSubscriptionOfferDetails: List<ProductDetails.SubscriptionOfferDetails>? = null
    private var monthProductDetails: ProductDetails? = null
    private var monthFormattedPrice = ""
    private var isGuide = false
    private var isChoseYear = false
    private var disFormatted = ""
    private var videoPagerAdapter:VideoPagerAdapter?=null
    private var isAppInBackground = false
    private var currentVideoPosition = 0
    private var videoPlaybackPosition = 0 // 记录播放进度
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)

        isGuide = intent.extras?.getBoolean("isGuide") ?: false
        initListener()

        binding.chargedText.text = getString(
            R.string.you_be_charged, get3Day()
        )
        //设置默认价格
        binding.yearlyAverageValueText.text =  defaultYearPrice
        binding.yearlyValueText.text = getString(
            R.string.months_year_text, extractAndCalculateDailyPriceToMonth(defaultYearPrice)
        )
        val dem = calculateSavingsPercentageFromStrings(
            defaultYearPrice,
            defaultWeekPrice,
            12
        )?.toInt()
        if (dem != null) {
            binding.freeText.text = getString(
                R.string.save_text, "${dem}%"
            )
        }

        binding.weeklyAverageValueText.text = defaultWeekPrice
        binding.weeklyValueText.text = getString(
            R.string.day_week_text,
            extractAndCalculateDailyPriceToWeekDay(defaultWeekPrice)
        )
        binding.atAnyText.text = getString(
            R.string.you_can_unsubscribe2,
            "US$3.99"
        )

        getDetails()

        val params = binding.videoLayout.layoutParams as ViewGroup.MarginLayoutParams
        params.width = ScreenUtil.getWidthPixels(this)
        params.height = (ScreenUtil.getWidthPixels(this)*1.77).toInt()
        params.setMargins(0,(-(ScreenUtil.getScreenHeightByMetrics(this)*0.1)).toInt(),0,0)
        binding.videoLayout.layoutParams = params

        val params2 = binding.freeDesLayout.layoutParams as ViewGroup.MarginLayoutParams
        params2.width = ScreenUtil.getWidthPixels(this)
        params2.height = (ScreenUtil.getWidthPixels(this)*1.77).toInt()
        params2.setMargins(0,(-(ScreenUtil.getScreenHeightByMetrics(this)*0.1)).toInt(),0,0)

        binding.freeDesLayout.layoutParams = params2

//        val params3 = binding.xImg.layoutParams as ViewGroup.MarginLayoutParams
//        params3.setMargins(0,((ScreenUtil.getScreenHeightByMetrics(this)*0.2)).toInt(),0,0)
//        binding.xImg.layoutParams = params3
//        params.setMargins(0,(-(ScreenUtil.getScreenHeightByMetrics(this)*0.26)).toInt(),0,0)


        initVideo()

        setupMarqueeTextViews(binding.bulletLayout1,binding.bulletLayout2,binding.bulletLayout3)

//        val animation = AnimationUtils.loadAnimation(this, R.anim.vip_breathing_animation)
//        binding.subscroptionText.startAnimation(animation)

    }

    override fun useDefaultImmersive() {
        super.useDefaultImmersive()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables", "StringFormatInvalid")
    private fun initListener() {
        onBackPressedDispatcher.addCallback {
            goToAc(VipDiscountAc::class.java) {
                putExtra("isGuide", isGuide)
                putExtra("originalPrice", yearFormattedPrice)
            }
            finish()
        }
        binding.vipSwitch.setOnCheckedChangeListener { _, b ->
            if (b) {
                isChoseYear = false
                binding.videoLayout.isVisible = false
                binding.freeDesLayout.isVisible = true
                binding.dotsContainer.isVisible = false
                binding.yearLayout.background = getDrawable(R.drawable.bg_style_gray_r5)
                binding.weekLayout.background = getDrawable(R.drawable.bg_vip_style_chose)
//                binding.rootLayout.background = getDrawable(R.drawable.bg_style_vip_shade)

                binding.atAnyText.text = getString(
                    R.string.day_free_perweek,
                    monthFormattedPrice.ifEmpty { defaultWeekPrice }
                )
                binding.subscroptionText.text = getString(R.string.start_my_free)
                binding.cancelText.text =  getString(R.string.no_payment_due_now)
            } else {
                if (!isChoseYear) {
                    binding.atAnyText.text = getString(
                        R.string.per_week_sub,
                        monthFormattedPrice.ifEmpty { defaultWeekPrice }
                    )
                    binding.videoLayout.isVisible = true
                    binding.freeDesLayout.isVisible = false
//                    binding.rootLayout.background = null
                    binding.dotsContainer.isVisible = true
                }
                binding.subscroptionText.text = getString(R.string.Subscription)
                binding.cancelText.text =  getString(R.string.cancel_anytime)

            }
        }
        binding.xImg.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.subscroptionText.setOnClickListener {
            pay()
        }

        binding.yearLayout.setOnClickListener {
            binding.videoLayout.isVisible = true
            binding.freeDesLayout.isVisible = false

            binding.dotsContainer.isVisible = binding.videoLayout.isVisible
            isChoseYear = true
            binding.yearLayout.background = getDrawable(R.drawable.bg_vip_style_chose)
            binding.weekLayout.background = getDrawable(R.drawable.bg_style_gray_r5)
//            binding.rootLayout.background = null

            binding.atAnyText.text = getString(
                R.string.you_can_unsubscribe2,
                yearFormattedPrice.ifEmpty { defaultYearPrice }
            )
            binding.subscroptionText.text = getString(R.string.Subscription)
            binding.cancelText.text =  getString(R.string.cancel_anytime)
        }
        binding.weekLayout.setOnClickListener {
            isChoseYear = false


            if (binding.vipSwitch.isChecked) {
                binding.videoLayout.isVisible = false
                binding.freeDesLayout.isVisible = true
//                binding.rootLayout.background = getDrawable(R.drawable.bg_style_vip_shade)
                binding.subscroptionText.text = getString(R.string.start_my_free)
                binding.cancelText.text =  getString(R.string.no_payment_due_now)
            } else {
                binding.videoLayout.isVisible = true
                binding.freeDesLayout.isVisible = false
//                binding.rootLayout.background = null
                binding.subscroptionText.text = getString(R.string.Subscription)
                binding.cancelText.text =  getString(R.string.cancel_anytime)
            }
            binding.dotsContainer.isVisible = binding.videoLayout.isVisible

            binding.yearLayout.background = getDrawable(R.drawable.bg_style_gray_r5)
            binding.weekLayout.background = getDrawable(R.drawable.bg_vip_style_chose)

            if (binding.vipSwitch.isChecked) {
                binding.atAnyText.text = getString(
                    R.string.day_free_perweek,
                    monthFormattedPrice.ifEmpty { defaultWeekPrice }
                )
            } else {
                binding.atAnyText.text = getString(
                    R.string.per_week_sub,
                    monthFormattedPrice.ifEmpty { defaultWeekPrice }
                )
            }

        }
        binding.termsText.setOnClickListener {
            OpenAgreementUtils.openTerms(this)
        }
        binding.privacyText.setOnClickListener {
            OpenAgreementUtils.openPrivacy(this)
        }
        binding.RestoreText.setOnClickListener {
            pay()
        }
    }

    private fun initVideo() = with(binding){
        // 初始化视频 URI 列表
        val videoUris = listOf(
            Uri.parse("android.resource://${packageName}/${R.raw.vip_video1}"),
            Uri.parse("android.resource://${packageName}/${R.raw.vip_video3}"),
            Uri.parse("android.resource://${packageName}/${R.raw.vip_video2}"),
        )
        videoPagerAdapter = VideoPagerAdapter(this@VipBuyDesAc, videoUris)
        viewPager.adapter = videoPagerAdapter
//        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
//            override fun onPageSelected(position: Int) {
//                // 仅播放当前页视频:ml-citation{ref="2,4" data="citationList"}
//                playCurrentVideo(position)
//                updateDots(position % 3)
//            }
//        })
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                currentVideoPosition = position
                // 暂停旧视频
                (viewPager.getChildAt(0) as? RecyclerView)?.let {
                    val oldHolder = it.findViewHolderForAdapterPosition(videoPlaybackPosition)
                            as? VideoPagerAdapter.VideoViewHolder
                    oldHolder?.videoView?.pause()
                }
                // 播放新视频
                playCurrentVideo(position)
                updateDots(position % 3)
            }
        })
        setupDots()
    }

    private fun playCurrentVideo(position: Int) {
        (binding.viewPager.getChildAt(0) as? RecyclerView)?.let {
            val holder = it.findViewHolderForAdapterPosition(position) as? VideoPagerAdapter.VideoViewHolder
            holder?.videoView?.start()
        }
    }

    private fun setupDots() {
        val dots = arrayOfNulls<ImageView>(3)
        binding.dotsContainer.removeAllViews()
        for (i in 0 until 3) {
            dots[i] = ImageView(this).apply {
                setImageResource(R.drawable.dot_unselected_vip)
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    setMargins(10, 0, 10, 0)
                }
            }
            binding.dotsContainer.addView(dots[i])
        }
        // 默认选中第一个圆点
        if (dots.isNotEmpty()) {
            dots[0]?.setImageResource(R.drawable.dot_selected_vip)
        }
    }

    private fun updateDots(position: Int) {
        for (i in 0 until binding.dotsContainer.childCount) {
            val dot = binding.dotsContainer.getChildAt(i) as ImageView
            dot.setImageResource(
                if (i == position) R.drawable.dot_selected_vip else R.drawable.dot_unselected_vip
            )
        }
    }

    private fun getDetails() {

        lifecycleScope.launch {
            yearProductDetails = GooglePayUtil.queryProduct(vipProductYear)
            yearSubscriptionOfferDetails = yearProductDetails?.subscriptionOfferDetails
            yearProductDetails?.subscriptionOfferDetails?.forEach {
                val pricingPhase = it.pricingPhases.pricingPhaseList[0]
//                when (it.basePlanId) {
//                    SUB_YEAR_PLAN_ID -> {
                yearFormattedPrice = pricingPhase.formattedPrice
                binding.yearlyValueText.text = getString(
                    R.string.months_year_text, extractAndCalculateDailyPriceToMonth(yearFormattedPrice)
                )
                binding.yearlyAverageValueText.text = yearFormattedPrice
                binding.atAnyText.text = getString(
                    R.string.you_can_unsubscribe2,
                    yearFormattedPrice
                )

                if (monthFormattedPrice.isNotEmpty()) {
                    runCatching {
                        val dem = calculateSavingsPercentageFromStrings(
                            yearFormattedPrice,
                            disFormatted,
                            12
                        )?.toInt()
                        if (dem != null) {
                            binding.freeText.text = getString(
                                R.string.save_text, "${dem}%"
                            )
                        }
                    }
//                        }
//                    }
                }
            }
        }

        lifecycleScope.launch {
            monthProductDetails = GooglePayUtil.queryProduct(vipProductWeek)
            monthSubscriptionOfferDetails = monthProductDetails?.subscriptionOfferDetails
            monthSubscriptionOfferDetails?.let {
                binding.freeLayout.isVisible = it.size > 1
            }

            monthProductDetails?.subscriptionOfferDetails?.forEach {
                val pricingPhase = it.pricingPhases.pricingPhaseList[0]

                "monthProductDetails.formattedPrice ${pricingPhase.formattedPrice} priceAmountMicros ${pricingPhase.priceAmountMicros}".d()
//                when (it.basePlanId) {
//                    SUB_WEEK1_PLAN_ID -> {
                monthFormattedPrice = pricingPhase.formattedPrice
                binding.weeklyAverageValueText.text = monthFormattedPrice
                binding.weeklyValueText.text = getString(
                    R.string.day_week_text,
                    extractAndCalculateDailyPriceToWeekDay(monthFormattedPrice)
                )
                disFormatted = if (monthFormattedPrice.contains("Free")) {
                    it.pricingPhases.pricingPhaseList[1].formattedPrice

                } else {
                    pricingPhase.formattedPrice
                }
                if (yearFormattedPrice.isNotEmpty()) {
                    runCatching {
                        val dem = calculateSavingsPercentageFromStrings(
                            yearFormattedPrice,
                            disFormatted,
                            12
                        )?.toInt()
                        if (dem != null) {
                            binding.freeText.text = getString(
                                R.string.save_text, "${dem}%"
                            )
                        }
                    }
//                        }
//                    }
                }
            }
        }
    }


    private fun pay() {
        if (isChoseYear) {
            FIRBASE_SUB_PRODUCT_ID = vipProductYear
            SUB_PRODUCT_ID = vipProductYear
            google_pay_id = vipProductYear

            yearSubscriptionOfferDetails?.forEach {
                SUB_CURRENCY = it.pricingPhases.pricingPhaseList[0].priceCurrencyCode
                SUB_PRICE_VALUE =
                    parsePriceString(it.pricingPhases.pricingPhaseList[0].formattedPrice)

//                if (it.basePlanId == SUB_YEAR_PLAN_ID) {
                GooglePayUtil.pay(this, it.offerToken, yearProductDetails!!)
//                }
            }
        } else {
            monthSubscriptionOfferDetails?.let {
                FIRBASE_SUB_PRODUCT_ID = vipProductWeek


                if (binding.vipSwitch.isChecked) {
                    if (it.size > 1) {
                        SUB_PRODUCT_ID = "免费3天_${vipProductWeek}"
                        SUB_PRICE_VALUE = 0.0

                    } else {
                        SUB_PRODUCT_ID = vipProductWeek
                        SUB_PRICE_VALUE =
                            parsePriceString(it[0].pricingPhases.pricingPhaseList[0].formattedPrice)
                    }
                    google_pay_id = SUB_PRODUCT_ID
                    SUB_CURRENCY = it[0].pricingPhases.pricingPhaseList[0].priceCurrencyCode
                    GooglePayUtil.pay(this, it[0].offerToken, monthProductDetails!!)
                } else {
                    SUB_PRODUCT_ID = vipProductWeek
                    google_pay_id = SUB_PRODUCT_ID
                    if (it.size > 1) {
                        SUB_CURRENCY = it[1].pricingPhases.pricingPhaseList[0].priceCurrencyCode
                        SUB_PRICE_VALUE =
                            parsePriceString(it[1].pricingPhases.pricingPhaseList[0].formattedPrice)
                        GooglePayUtil.pay(this, it[1].offerToken, monthProductDetails!!)
                    } else {
                        SUB_CURRENCY = it[0].pricingPhases.pricingPhaseList[0].priceCurrencyCode
                        SUB_PRICE_VALUE =
                            parsePriceString(it[0].pricingPhases.pricingPhaseList[0].formattedPrice)
                        GooglePayUtil.pay(this, it[0].offerToken, monthProductDetails!!)
                    }
                }

            }
        }

    }

    private fun get3Day(): String {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DATE, 3) // 加 3 天
        val sdf = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
        val formattedDate = sdf.format(calendar.time)
        return formattedDate
    }


    private fun setupMarqueeTextViews(vararg textViews: View) {

        // 获取屏幕宽度
        val screenWidth = resources.displayMetrics.widthPixels.toFloat()

        textViews.forEachIndexed { index, tv ->
            // 初始位置：屏幕右侧外 + 自身宽度（避免重叠）
            tv.translationX = screenWidth + tv.width * index
//            tv.translationX = (tv.width * index).toFloat()

            // 创建位移动画
            val animator = ObjectAnimator.ofFloat(
                tv,
                "translationX",
                -screenWidth - tv.width * (textViews.size - index) // 目标位置：屏幕左侧外
            ).apply {
                duration = 7000L + index * 1000L // 不同速度（5秒/6秒/7秒）
                interpolator = LinearInterpolator()
                repeatCount = ObjectAnimator.INFINITE
                start()
            }

            // 循环逻辑：动画结束时重置位置
            animator.addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    if (tv.translationX <= -tv.width) {
                        tv.translationX = screenWidth
                        animator.start()
                    }
                }
            })
        }
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isVip") {
            finish()
        }
    }


    class VideoPagerAdapter(
        private val context: Context,
        private val videoUris: List<Uri>
    ) : RecyclerView.Adapter<VideoPagerAdapter.VideoViewHolder>() {

        // 记录当前播放位置
        var currentPlayingPosition = -1

        inner class VideoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val videoView: VideoView = itemView.findViewById(R.id.videoView)
            init {
                videoView.setOnPreparedListener { mediaPlayer ->
                    mediaPlayer.isLooping = true
                }
            }
        }
        override fun onViewAttachedToWindow(holder: VideoViewHolder) {
            super.onViewAttachedToWindow(holder)
            // 当 View 重新可见时恢复播放
            if (holder.adapterPosition == currentPlayingPosition) {
                holder.videoView.start()
            }
        }

        override fun onViewDetachedFromWindow(holder: VideoViewHolder) {
            super.onViewDetachedFromWindow(holder)
            // 当 View 不可见时暂停
            holder.videoView.pause()
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.vip_viewpager_item, parent, false)
            return VideoViewHolder(view)
        }

        override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
            val uri = videoUris[position]

            // 设置视频源
            holder.videoView.setVideoURI(uri)
            holder.videoView.start()
            holder.videoView.setOnCompletionListener {
                holder.videoView.seekTo(0)
                holder.videoView.start()
            }


            // 点击播放/暂停（可选）
//        holder.itemView.setOnClickListener {
//            if (holder.videoView.isPlaying) {
//                holder.videoView.pause()
//            } else {
//                holder.videoView.start()
//                holder.ivThumbnail.visibility = View.GONE
//            }
//        }
        }

        override fun onViewRecycled(holder: VideoViewHolder) {
            super.onViewRecycled(holder)
//            holder.videoView.apply {
//                setVideoURI(null)
//                clearAnimation()
//            }
        }
        override fun getItemCount(): Int = videoUris.size

    }
    private fun pauseCurrentVideo() {
        (binding.viewPager.getChildAt(0) as? RecyclerView)?.let { recyclerView ->
            val holder = recyclerView.findViewHolderForAdapterPosition(currentVideoPosition)
                    as? VideoPagerAdapter.VideoViewHolder
            holder?.let {
                videoPlaybackPosition = it.videoView.currentPosition
                it.videoView.pause()
            }
        }
    }

    private fun resumeCurrentVideo() {
        (binding.viewPager.getChildAt(0) as? RecyclerView)?.let { recyclerView ->
            val holder = recyclerView.findViewHolderForAdapterPosition(currentVideoPosition)
                    as? VideoPagerAdapter.VideoViewHolder
            holder?.videoView?.apply {
                seekTo(videoPlaybackPosition)
                start()
            }
        }
    }
    override fun onPause() {
        super.onPause()
        pauseCurrentVideo()
        isAppInBackground = true
    }

    override fun onResume() {
        super.onResume()
        if (isAppInBackground) {
            resumeCurrentVideo()
            isAppInBackground = false
        }
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()
//        binding.videoView.suspend()
        EventBus.getDefault().unregister(this)
    }
}
